//---------------------------------------------------------------------
// Authors: jachymko
//
// Description: Shared parsing methods.
//
// Creation Date: Jan 25, 2006
//
//---------------------------------------------------------------------
using System;
using System.Text;
using System.Text.RegularExpressions;

namespace BGShell.PowerShell.TabExpansion.Parsers
{
    internal static class TabExpansionParser
    {
        public static string ExtractLastStatement(string line)
        {
            line = RemoveCommentsAndStrings(line);

            string[] statements = line.Split('|', ';');
            string command = statements[statements.Length - 1];

            Match m = _findBlock.Match(command);
            if (m.Success)
            {
                command = m.Groups[1].Value;
            }

            m = _findExpr.Match(command);
            if (m.Success)
            {
                command = m.Groups[1].Value;
            }

            return command.Trim().Split()[0];
        }

        public static string RemoveCommentsAndStrings(string line)
        {
            const string Null = " $null ";
            const char SingleQuote = '\'';
            const char DoubleQuote = '"';

            bool inDouble = false;
            bool inSingle = false;

            StringBuilder result = new StringBuilder();

            for (int i = 0; i < line.Length; i++)
            {
                char ch = line[i];

                if (inDouble && ch == DoubleQuote)
                {
                    inDouble = false;
                    result.Append(Null);
                    continue;
                }

                if (inSingle && ch == SingleQuote)
                {
                    inSingle = false;
                    result.Append(Null);
                    continue;
                }

                if (inSingle || inDouble)
                {
                    continue;
                }

                if (ch == DoubleQuote)
                {
                    inDouble = true;
                    continue;
                }

                if (ch == SingleQuote)
                {
                    inSingle = true;
                    continue;
                }

                if ((i < line.Length - 1) && (ch == '@') && (line[i + 1] == DoubleQuote))
                {
                    // a multiline "here-string"
                    break;
                }

                if (ch == '#')
                {
                    // comment
                    break;
                }

                result.Append(ch);
            }

            return result.ToString();
        }

        private static readonly Regex _findBlock = new Regex(@"\{([^\{\}]*)$");
        private static readonly Regex _findExpr = new Regex(@"\(([^()]*)$");
    }
}
